package org.abratuhi.kvngroupware.scenario.gui;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.util.Properties;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SpringLayout;
import javax.swing.table.DefaultTableModel;

import org.abratuhi.kvngroupware.KVNGroupwareClientAction;
import org.abratuhi.kvngroupware.jokemanager.manager.JokeManager;
import org.abratuhi.kvngroupware.jokemanager.model.Joke;
import org.abratuhi.kvngroupware.login.manager.LoginManager;
import org.abratuhi.kvngroupware.network.MessageSender;
import org.abratuhi.kvngroupware.scenario.manager.ScenarioManager;
import org.abratuhi.kvngroupware.scenario.model.Scenario;
import org.abratuhi.kvngroupware.spring.SpringUtilities;
import org.abratuhi.kvngroupware.user.model.User;
import org.abratuhi.kvngroupware.widget.AbstractWorkWidget;
import org.jdom.Element;

@SuppressWarnings("serial")
public class GuiScenario extends AbstractWorkWidget{
	
	LoginManager loginmanager;
	JokeManager jokemanager;
	ScenarioManager scenariomanager;
	
	String[] tableColumns = new String[]{};
	DefaultTableModel modelJokes = new DefaultTableModel();
	DefaultTableModel modelScenario = new DefaultTableModel();
	JTable tableJokes = new JTable(modelJokes);
	JTable tableScenario = new JTable(modelScenario);
	JTextArea textJoke = new JTextArea();
	
	JButton buttonAddJoke = new JButton("→");
	JButton buttonRemoveJoke = new JButton("←");
	JButton buttonUpJoke = new JButton("↑");
	JButton buttonDownJoke = new JButton("↓");
	
	public GuiScenario(String frameid, String frametitle, MessageSender sender, Properties locale, 
			LoginManager loginmanager, JokeManager jokemanager, ScenarioManager scenariomanager){
		super(frameid, frametitle, sender, locale);
		
		this.setExitMessage(sender.createMessage(
				"type,action,userId,teamId,scenarioId",
				"scenario,leave,"+loginmanager.getUser().getId()+","+loginmanager.getTeam().getId()+","+frameid,
				"", 
				new Element[]{scenariomanager.get(frameid).toElement()}));
		
		this.loginmanager = loginmanager;
		this.jokemanager = jokemanager;
		this.scenariomanager = scenariomanager;
		
		this.tableColumns = locale.getProperty("scenario.columns").split(",");
		
		for(int i=0; i<tableColumns.length; i++) modelJokes.addColumn(tableColumns[i]);
		tableJokes.getColumnModel().getColumn(0).setPreferredWidth(10);
		tableJokes.getColumnModel().getColumn(1).setMinWidth(200);
		tableJokes.getColumnModel().getColumn(2).setPreferredWidth(50);
		tableJokes.getColumnModel().getColumn(2).setMaxWidth(50);
		tableJokes.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		for(int i=0; i<tableColumns.length; i++) modelScenario.addColumn(tableColumns[i]);
		tableScenario.getColumnModel().getColumn(0).setPreferredWidth(10);
		tableScenario.getColumnModel().getColumn(1).setMinWidth(200);
		tableScenario.getColumnModel().getColumn(2).setPreferredWidth(50);
		tableScenario.getColumnModel().getColumn(2).setMaxWidth(50);
		tableScenario.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		textJoke.setColumns(20);
		textJoke.setRows(6);
		
		buttonAddJoke.setAction(new AddAction("→", null, null, null));
		buttonRemoveJoke.setAction(new RemoveAction("←", null, null, null));
		buttonUpJoke.setAction(new UpAction("↑", null, null, null));
		buttonDownJoke.setAction(new DownAction("↓", null, null, null));
		
		Box boxB1 = Box.createVerticalBox();
		boxB1.add(Box.createGlue());
		boxB1.add(buttonAddJoke);
		boxB1.add(buttonRemoveJoke);
		boxB1.add(Box.createVerticalStrut(10));
		boxB1.add(buttonUpJoke);
		boxB1.add(buttonDownJoke);
		boxB1.add(Box.createGlue());
		
		JPanel panelLU = new JPanel();
		panelLU.setLayout(new SpringLayout());
		panelLU.add(new JScrollPane(tableJokes));
		panelLU.add(boxB1);
		SpringUtilities.makeCompactGrid(panelLU, 1, 2, 0, 0, 0, 0);
		
		JPanel panelL = new JPanel();
		panelL.setLayout(new SpringLayout());
		panelL.add(panelLU);
		panelL.add(new JScrollPane(textJoke));
		SpringUtilities.makeCompactGrid(panelL, 2, 1, 0, 0, 0, 0);
		
		Box boxB2 = Box.createVerticalBox();
		boxB2.add(Box.createGlue());
		//boxB2.add(buttonUpJoke);
		//boxB2.add(buttonDownJoke);
		boxB2.add(Box.createGlue());
		
		JPanel panelRU = new JPanel();
		panelRU.setLayout(new SpringLayout());
		panelRU.add(new JScrollPane(tableScenario));
		panelRU.add(boxB2);
		SpringUtilities.makeCompactGrid(panelRU, 1, 2, 0, 0, 0, 0);
		
		JPanel panelR = new JPanel();
		panelR.setLayout(new SpringLayout());
		panelR.add(panelRU);
		SpringUtilities.makeCompactGrid(panelR, 1, 1, 0, 0, 0, 0);
		
		JSplitPane splitV = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panelL, panelR);
		
		this.setLayout(new SpringLayout());
		this.setPreferredSize(new Dimension(400, 300));
		this.add(splitV);
		SpringUtilities.makeCompactGrid(this, 1, 1, 0, 0, 0, 0);
	}
	
	public void paint(Graphics g){
		super.paint(g);
		
		//User user = loginmanager.getUser();
		String[] jokeIds = jokemanager.getkeys();
		Scenario scenario = scenariomanager.get(frameid);
		
		// jokes
		int nrows = modelJokes.getRowCount();
		for(int i=0; i<nrows; i++){
			modelJokes.removeRow(0);
		}
		for(int i=0; i<jokeIds.length; i++){
			Joke joke = jokemanager.get(jokeIds[i]);
			modelJokes.addRow(new String[]{joke.getId(), joke.getText(), joke.getRating()});
		}
		
		// scenario
		nrows = modelScenario.getRowCount();
		for(int i=0; i<nrows; i++){
			modelScenario.removeRow(0);
		}
		for(int i=0; i<scenario.size(); i++){
			Joke joke = jokemanager.get(scenario.get(i));
			modelScenario.addRow(new String[]{joke.getId(), joke.getText(), joke.getRating()});
		}
	}
	
	
	class AddAction extends KVNGroupwareClientAction{
		public AddAction(String text, ImageIcon icon, String desc,
				Integer mnemonic) {
			super(text, icon, desc, mnemonic);
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			User user = loginmanager.getUser();
			Joke joke = jokemanager.get((String) tableJokes.getValueAt(tableJokes.getSelectedRow(), 0));
			Scenario scenario = scenariomanager.get(frameid);
			
			sender.sendMessage(sender.createMessage(
					"type,action,userId,scenarioId,jokeId",
					"scenario_joke,add,"+user.getId()+","+scenario.getId()+","+joke.getId(),
					"",
					new Element[0]));
		}
	}
	
	class RemoveAction extends KVNGroupwareClientAction{
		public RemoveAction(String text, ImageIcon icon, String desc,
				Integer mnemonic) {
			super(text, icon, desc, mnemonic);
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			User user = loginmanager.getUser();
			Joke joke = jokemanager.get((String) tableScenario.getValueAt(tableScenario.getSelectedRow(), 0));
			Scenario scenario = scenariomanager.get(frameid);
			
			sender.sendMessage(sender.createMessage(
					"type,action,userId,scenarioId,jokeId",
					"scenario_joke,remove,"+user.getId()+","+scenario.getId()+","+joke.getId(),
					"",
					new Element[0]));
		}
	}
	
	class UpAction extends KVNGroupwareClientAction{
		public UpAction(String text, ImageIcon icon, String desc,
				Integer mnemonic) {
			super(text, icon, desc, mnemonic);
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			User user = loginmanager.getUser();
			Joke joke = jokemanager.get((String) tableScenario.getValueAt(tableScenario.getSelectedRow(), 0));
			Scenario scenario = scenariomanager.get(frameid);
			
			sender.sendMessage(sender.createMessage(
					"type,action,userId,scenarioId,jokeId",
					"scenario_joke,up,"+user.getId()+","+scenario.getId()+","+joke.getId(),
					"",
					new Element[0]));
		}
	}
	
	class DownAction extends KVNGroupwareClientAction{
		public DownAction(String text, ImageIcon icon, String desc,
				Integer mnemonic) {
			super(text, icon, desc, mnemonic);
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			User user = loginmanager.getUser();
			Joke joke = jokemanager.get((String) tableScenario.getValueAt(tableScenario.getSelectedRow(), 0));
			Scenario scenario = scenariomanager.get(frameid);
			
			sender.sendMessage(sender.createMessage(
					"type,action,userId,scenarioId,jokeId",
					"scenario_joke,down,"+user.getId()+","+scenario.getId()+","+joke.getId(),
					"",
					new Element[0]));
		}
	}
	
	
	

	/*
	public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
		public MyComboBoxRenderer(String[] items) {
			super(items);
		}

		public Component getTableCellRendererComponent(JTable table, Object value,
				boolean isSelected, boolean hasFocus, int row, int column) {
			if (isSelected) {
				setForeground(table.getSelectionForeground());
				super.setBackground(table.getSelectionBackground());
			} else {
				setForeground(table.getForeground());
				setBackground(table.getBackground());
			}

			// Select the current value
			setSelectedItem(value);
			return this;
		}
	}

	public class MyComboBoxEditor extends DefaultCellEditor {
		public MyComboBoxEditor(String[] items) {
			super(new JComboBox(items));
		}
	}*/
	/*
	public static void main(String [] args){
		JFrame f = new JFrame();
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
		
		JTable table = new JTable();
	    DefaultTableModel model = (DefaultTableModel)table.getModel();
	    
	    // Add some columns
	    model.addColumn("A", new Object[]{"item1"});
	    model.addColumn("B", new Object[]{"item2"});
	    
	    // These are the combobox values
	    String[] values = new String[]{"item1", "item2", "item3"};
	    
	    // Set the combobox editor on the 1st visible column
	    int vColIndex = 0;
	    TableColumn col = table.getColumnModel().getColumn(vColIndex);
	    col.setCellEditor(new GUIScenarioManager().new MyComboBoxEditor(values));
	    
	    // If the cell should appear like a combobox in its
	    // non-editing state, also set the combobox renderer
	    col.setCellRenderer(new GUIScenarioManager().new MyComboBoxRenderer(values));
	    
	    f.add(table);
	    f.pack();
	}
	*/

}
